<template>
  <div id='exchange_up'>
    <Row type='flex' justify='center' style="padding:60px 100px">
      <Col style="width: 1000px;">
        <Steps :current="current">
          <Step title="选择兑换商品"
                class="prev"></Step>
          <Step title="完善兑换信息"
                class="prev"></Step>
          <Step title="完成上架"
                class="complate"></Step>
        </Steps>
      </Col>
    </Row>
    <div class="common-style level1" style="width: 900px" v-show='current === 0'>
      <div class="guide">
        <p></p>
        <span>选择兑换商品</span>
      </div>
      <Form inline ref="formValidate1" :model="formValidate1" :rules="ruleValidate1" :label-width="110" style="width: 900px;">
        <!-- <FormItem label="商品分类：" prop="involvedType">
          <Input v-model="formValidate1.involvedType[0]" placeholder="请输入" style="width: 120px" disabled></Input>
          <span style="color:#DCDEE2;margin: 0 9px">-</span>
          <Input v-model="formValidate1.involvedType[1]" placeholder="请输入" style="width: 120px" disabled></Input>
        </FormItem>
        <FormItem label="是否虚拟商品：" prop="isShow" :label-width='180'>
          <RadioGroup v-model="formValidate1.isShow" size="large">
            <Radio label="1">是</Radio>
            <Radio label="0" style="margin-left:50px">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="所属类型：" prop="relateType">
          <Input :value="formValidate1.relateType" placeholder="请输入" class="input-width" disabled></Input>
        </FormItem> -->
        <FormItem label="兑换商品分类：" prop="matchClassify">
          <Select v-model="formValidate1.matchClassify" class="input-width" @on-change='changeExchangeType'>
            <Option v-for="(item, index) in matchClassifyList" :value="item.value" :key="index">{{item.label}}</Option>
          </Select>
        </FormItem>
        <FormItem label="兑换商品：" prop="exchangeGoods" :label-width='180'>
          <Button @click="addProduct">添加商品+</Button>
        </FormItem>
        <FormItem label="所选商品：" prop="selectGoods">
          <Table :columns="columns" :data="formValidate1.selectGoods">
            <template slot-scope="{ row }" slot="action">
              <i class="iconsys icondel" title="删除" @click='delSelected'></i>
            </template>
            <template slot-scope="{ row }" slot="iconPath">
              <div v-if='row.iconPath' style="margin: 15px;">
                <img :src="row.iconPath" alt="" style="width: 60px;height: 60px;display: block;">
              </div>
            </template>
          </Table>
        </FormItem>
        <FormItem>
          <div style="margin-top: 20px">
            <Button type="primary" @click="submitStep1">下一步，完善兑换信息</Button>
          </div>
        </FormItem>
      </Form>
      <drawer-commodity
      :selectList='formValidate1.selectGoods'
      :title='title'
      :type='type'
      :value='drawShow'
      :matchClassify='formValidate1.matchClassify'
      @sureSelect='sureSelect' @closeDraw='closeDraw'></drawer-commodity>
    </div>
    <div class="common-style level2" style="width: 900px" v-show='current === 1'>
      <div class="guide">
        <p></p>
        <span>价格信息</span>
      </div>
      <Form inline ref="formValidate2" :model="formValidate2" :rules="ruleValidate2" :label-width="110" style="width: 900px;">
        <FormItem label="兑换商品名称：" prop="exchangeName">
          <Input placeholder="请输入" v-model='formValidate2.exchangeName' class="input-width" disabled></Input>
        </FormItem>
        <FormItem label="可售库存：" prop="inventory" :label-width="180">
          <Input placeholder="请输入" v-model='formValidate2.inventory' class="input-width" :maxlength='4' :disabled="notControl" @on-keyup="filterNum('inventory')" @on-blur="filterNum('inventory')"></Input>
        </FormItem>
        <Checkbox v-model="notControl" style="margin: 7px 0 0 10px">不限</Checkbox>
        <FormItem label="兑换类型：" prop="exchangeType">
          <Select v-model="formValidate2.exchangeType" class="input-width">
            <Option v-for="(item, index) in exchangeTypeList" :value="item.value" :key="index">{{item.label}}</Option>
          </Select>
        </FormItem>
        <FormItem label="兑换数量：" prop="exchangeNum" :label-width="180">
          <Input placeholder="请输入" v-model='formValidate2.exchangeNum' :maxlength='4' class="input-width" @on-keyup="filterNum('exchangeNum')" @on-blur="filterNum('exchangeNum')"></Input>
        </FormItem>
        <FormItem label="上架时间：" prop="upTime">
          <DatePicker :value="formValidate2.upTime" type="datetime" :editable="false" placeholder="请选择" class="input-width" @on-change="activityStartChange" :options="activityStartOptions"></DatePicker>
        </FormItem>
        <FormItem label="下架时间：" prop="downTime" :label-width="180">
          <DatePicker :value="formValidate2.downTime" type="datetime" :editable="false" placeholder="请选择" class="input-width" @on-change="activityEndChange" :options="activityEndOptions"></DatePicker>
        </FormItem>
        <FormItem label="兑换限制：" prop="exchangeControl">
          <Select v-model="formValidate2.exchangeControl" class="input-width">
            <Option v-for="(item, index) in exchangeControlList" :value="item.value" :key="index">{{item.label}}</Option>
          </Select>
        </FormItem>
        <FormItem label="等级限制：" prop="memberControl" :label-width="180">
          <Select v-model="formValidate2.memberControl" class="input-width">
            <Option value="-1">不限制</Option>
            <Option v-for="(item, index) in memberControlList" :value="item.memberLevel" :key="index">{{'V' + item.memberLevel}}</Option>
          </Select>
        </FormItem>
        <FormItem label="温馨提示：" prop="remark">
          <div ref="addEditor" class="rich-editor"></div>
          <!-- <Input v-model="formValidate2.remark" type="textarea" placeholder="请输入" :autosize="{minRows: 5,maxRows: 8}" style="width: 710px" /> -->
        </FormItem>
        <FormItem>
          <Button class="system-submit-btn" style="color: #2D8CF0;" @click='skipStep1'>上一步，完善商品信息</Button>
          <Button type="primary" class="system-submit-btn" style="margin-left: 15px" @click='submitStep2'>下一步，完成商品上下架</Button>
        </FormItem>
      </Form>
    </div>
    <div class="common-style level3" style="width: 900px;text-align: center;padding-top:50px" v-show='current === 2'>
      <div style="color: #18BE6B;">
        <Icon type="ios-checkmark-circle-outline" size='35' />
      </div>
        <h3 style="margin: 10px 0 50px 0">完成上架({{timeNum}})s</h3>
        <Button type="primary" @click="goBackList">返回兑换商品列表</Button>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import editor from '@/view/market/game-ticket/mixins.js'
import { routeEqual } from '@/libs/util'
import DrawerCommodity from '@/view/components/drawer-commodity/index.vue'
import { memberList, exchangeAdd } from '@/api/commondity/index'
export default {
  name: 'exchang_up',
  mixins: [editor],
  components: { DrawerCommodity },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    })
  },
  watch: {
    'notControl' (val) {
      if (val) {
        this.ruleValidate2.inventory.required = false
        this.formValidate2.inventory = ''
        this.$refs.formValidate2.validateField('inventory', valid => {})
        if (this.formValidate2.exchangeNum) {
          this.$refs.formValidate2.validateField('exchangeNum', valid => {})
        }
      } else {
        this.ruleValidate2.inventory.required = true
      }
    },
    current (val) {
      if (val === 2) {
        this.timeNum = 3
        this.timer = setInterval(() => {
          this.timeNum--
          if (this.timeNum === 0) {
            clearInterval(this.timer)
            this.handleReset()
          }
        }, 1000)
      }
    }
  },
  data () {
    return {
      submitLock: false,
      timer: '',
      timeNum: 3,
      type: '0',
      couponName: '',
      pageObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      title: '兑换商品列表',
      tableData: [], // 侧边栏table值
      columnsDraw: [],
      drawShow: false,
      current: 0,
      matchClassifyList: [
        { value: '0', label: '代金券' },
        { value: '1', label: '折扣券' }
      ],
      formValidate1: {
        matchClassify: '0', // 兑换商品分类
        exchangeGoods: '',
        selectGoods: []
      },
      ruleValidate1: {
        matchClassify: { required: true, message: '请选择兑换商品分类', trigger: 'change' },
        exchangeGoods: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (this.formValidate1.selectGoods.length > 0) {
              callback()
            } else {
              callback(new Error('请选择兑换商品'))
            }
          }
        },
        selectGoods: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (this.formValidate1.selectGoods.length > 0) {
              callback()
            } else {
              callback(new Error('所选商品不能为空'))
            }
          }
        }
      },
      exchangeTypeList: [
        { value: '0', label: '积分' }
      ],
      activityStartOptions: {},
      activityEndOptions: {},
      exchangeControlList: [
        { value: '-1', label: '不限制,活动全程' }
      ],
      memberControlList: [],
      notControl: false,
      formValidate2: {
        exchangeName: '', // 兑换商品名称
        inventory: '', // 可售库存
        exchangeType: '', // 兑换类型
        exchangeNum: '', // 兑换数量
        upTime: '',
        downTime: '',
        exchangeControl: '', // 兑换限制
        memberControl: '' // 等级限制
      },
      ruleValidate2: {
        exchangeName: { required: true, message: '兑换商品名称不能为空', trigger: 'change' },
        inventory: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (this.notControl) {
              callback()
            } else {
              if (!value) {
                callback(new Error('请输入可售库存'))
              } else {
                if (this.formValidate2.exchangeNum > this.formValidate2.inventory && this.formValidate2.exchangeNum) {
                  callback(new Error('可售库存不能小于兑换数量'))
                } else {
                  callback()
                }
              }
            }
          }
        },
        exchangeType: { required: true, message: '请选择兑换类型', trigger: 'change' },
        exchangeNum: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (this.notControl) {
              callback()
            } else {
              if (!value) {
                callback(new Error('请输入兑换数量'))
              } else {
                if (this.formValidate2.exchangeNum > this.formValidate2.inventory && this.formValidate2.inventory) {
                  callback(new Error('兑换数量要小于可售库存'))
                } else {
                  callback()
                }
              }
            }
          }
        },
        exchangeControl: { required: true, message: '请选择兑换限制', trigger: 'change' },
        memberControl: { required: true, message: '请选择等级限制', trigger: 'change' },
        upTime: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formValidate2.upTime).getTime()) {
              callback(new Error('请选择上架时间'))
            } else if (new Date(this.formValidate2.upTime).getTime() > new Date(this.formValidate2.downTime).getTime() || new Date(this.formValidate2.upTime).getTime() === new Date(this.formValidate2.downTime).getTime()) {
              callback(new Error('上架时间要小于下架时间'))
            } else {
              callback()
            }
          }
        },
        downTime: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formValidate2.downTime).getTime()) {
              callback(new Error('请选择下架时间'))
            } else if (new Date(this.formValidate2.upTime).getTime() > new Date(this.formValidate2.downTime).getTime() || new Date(this.formValidate2.upTime).getTime() === new Date(this.formValidate2.downTime).getTime()) {
              callback(new Error('下架时间要大于上架时间'))
            } else if (new Date().getTime() > new Date(this.formValidate2.downTime).getTime()) {
              callback(new Error('下架时间要大于当前系统时间'))
            } else {
              callback()
            }
          }
        }
      },
      columns: [
        {
          title: '商品图片',
          slot: 'iconPath'
        },
        {
          title: '商品名称',
          key: 'couponName'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ]
    }
  },
  methods: {
    filterNum (param) {
      this.formValidate2[param] = this.formValidate2[param].replace(/[^\d]/g, '')
      if (this.formValidate2[param].length > 1) {
        this.formValidate2[param] = this.formValidate2[param].replace(/[^\d]/g, '').replace(/^0{1,}/g, '')
      }
    },
    delSelected () {
      this.formValidate1.selectGoods = []
    },
    addProduct () {
      this.drawShow = true
    },
    closeDraw () {
      this.drawShow = false
    },
    changeExchangeType (val) {
      this.formValidate1.selectGoods = []
      this.formValidate2.exchangeName = ''
    },
    sureSelect (data) {
      this.formValidate1.selectGoods = []
      this.formValidate1.selectGoods = data
      this.$refs.formValidate1.validate()
    },
    next () {
      if (this.current === 2) {
        this.current = 0
      } else {
        this.current += 1
      }
    },
    getMemberList () {
      memberList({
        merchantId: this.$store.state.user.merchantId
      }).then(res => {
        if (res.data.status === 200) {
          this.memberControlList = res.data.data || []
          if (this.memberControlList.length > 0) {
            this.memberControlList = this.memberControlList.map(item => {
              return { memberLevel: item.memberLevel + '' }
            })
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    submitStep1 () {
      this.$refs.formValidate1.validate(valid => {
        if (valid) {
          this.next()
          this.formValidate2.exchangeName = this.formValidate1.selectGoods[0].couponName
          this.getMemberList()
        }
      })
    },
    skipStep1 () {
      this.current--
    },
    submitStep2 () {
      this.$refs.formValidate2.validate(valid => {
        if (valid) {
          if (this.submitLock) {
            return
          }
          this.submitLock = true
          let data = {
            merchantId: this.merchantId,
            couponId: this.formValidate1.selectGoods[0].couponId,
            couponName: this.formValidate1.selectGoods[0].couponName,
            couponType: this.formValidate1.matchClassify,
            imageUrl: this.formValidate1.selectGoods[0].iconPath,
            availableAmount: this.formValidate2.inventory ? this.formValidate2.inventory : this.notControl ? '-1' : '',
            exchangeType: this.formValidate2.exchangeType,
            price: this.formValidate2.exchangeNum,
            upTime: this.formValidate2.upTime,
            downTime: this.formValidate2.downTime,
            exchangeLimit: this.formValidate2.exchangeControl,
            levelLimit: this.formValidate2.memberControl,
            note: this.$editor.txt.html(),
            creatorId: this.userId,
            creatorName: this.userName
          }
          exchangeAdd(data).then(res => {
            this.submitLock = false
            if (res.data.status === 200) {
              this.next()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    },
    activityStartChange (time) {
      this.formValidate2.upTime = time
      this.activityEndOptions = {
        disabledDate (date) {
          return date.valueOf() < new Date(time.split(' ')[0]).getTime() - 24 * 3600 * 1000
        }
      }
    },
    activityEndChange (time) {
      this.formValidate2.downTime = time
      this.activityStartOptions = {
        disabledDate (date) {
          return date.valueOf() > new Date(time).getTime()
        }
      }
    },
    goBackList () {
      this.handleReset()
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'exchang_list'
        })
      })
    }
  },
  mounted () {
    this.createEditor(this.$refs.addEditor)
  }
}
</script>

<style lang="less">
#exchange_up{
  .input-width{
    width: 260px;
  }
  .btn{
    width: 72px;
  }
  .prev {
    width: 43% !important;
  }
  .complate {
    width: 14% !important;
  }
  .common-style{
    margin: 0 auto !important;
  }
  .guide{
    display: flex;
    margin-bottom: 30px;
    p {
      width: 8px;
      height: 20px;
      background: #2d8cf0;
      margin-right: 10px;
    }
  }
  .rich-editor{
    width: 710px;
    .w-e-text-container{
      height: 200px !important;
    }
  }
}
</style>
